package com.example.module_word.net

import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.sy.lib_secretkey.BaseCallBackListener
import com.sy.lib_secretkey.SecretkeyUtils
import kotlinx.coroutines.flow.flow
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object TianXingManage {
    private val apiService by lazy {
        Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl("https://apis.tianapi.com/")
            .build().create(TianXingApi::class.java)
    }

    private const val DEF_KEY = "WqNFTLZ5R1Q2pEFc1YXYw7BIzRfB/09u5sdwDBf3n37OCiBL6PQ2Np9nYIl0N9bE"
    private var apiKey = ""

    init {
        getKey()
    }

    /**
     * 获取天行数据的key
     */
    fun getKey(block: () -> Unit = {}) {
        if (apiKey.isEmpty()) {
            SecretkeyUtils.getSecretkey(
                DEF_KEY,
                "TXSJ_common_key",
                object : BaseCallBackListener<String> {
                    override fun onSuccess(p0: String) {
                        apiKey = p0
                        block.invoke()
                    }

                    override fun onFailed(p0: String?) {
                        ToastUtils.showShort("获取key错误")
                    }

                    override fun onHandlerStart() {

                    }

                })
        } else {
            block.invoke()
        }
    }

    /**
     * 英汉词典
     */
    suspend fun getDictionaryEntity(word:String) = flow {
        apiService.getDictionaryEntity(apiKey,word).apply {
            if (code == 200) {
                result?.let {
                    emit(result)
                }?:ToastUtils.showShort("未查询到该单词")
                LogUtils.dTag("英语一句话", result)
            } else {
                ToastUtils.showShort("未查询到该单词")
                LogUtils.dTag("英语一句话", msg)
            }
        }
    }
}